package com.suxin.spring;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author Tang
 * @classname SpringContextUtils
 * @description [  ]
 * @date 2021/11/4 16:02
 */
public class SpringContextUtils implements ApplicationContextAware {

    @Getter
    private ApplicationContext applicationContext;

    private static SpringContextUtils springContextUtils;

    private static final Object OBJECT_ = new Object();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        synchronized (OBJECT_) {
            OBJECT_.notify();
        }
        this.applicationContext = applicationContext;
    }

    public <T> T getBean(Class<T> tClass) {
        return springContextUtils().getBean(tClass);
    }

    public Object getBean(String name) {
        return springContextUtils().getBean(name);
    }

    public static SpringContextUtils springContextUtils() {
        if (springContextUtils == null) {
                synchronized (OBJECT_) {
                    try {
                        OBJECT_.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            springContextUtils = new SpringContextUtils();
        }
        return springContextUtils;
    }

}